import { toZipBlob } from '@/lib/utils';
import { request } from './request';
import { ProductInfo } from '@/lib/dianxiaomi';

export interface PageParams {
  pageNo: number;
  pageSize: number;
}

// 拉取特定页的产品文档对象
type getPageListDocumentOptions = {
  shopId: number;
  shopGroupId: string;
  searchType: number;
  searchValue: string;
  sortName: 2;
  sortValue: number;
  dxmState: 'offline';
  site: string;
  dxmOfflineState: 'waitPublish';
  productSearchType: number;
  fullCid: string;
  productStatus: string;
  quantityLift: string;
  quantityRight: string;
  advancedTime: number;
  timeLift: string;
  timeRight: string;
  priceLift: string;
  priceRight: string;
  createId: string;
  advancedSearch: string;
  commentType: number;
  commentContent: string;
  productStateValue: string;
} & PageParams;

export function getPageListDocument<T = Document>({ pageNo, pageSize }: PageParams) {
  return request<T, T>({
    url: 'api/popTemuProduct/pageList.htm',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: {
      pageNo,
      pageSize,
      shopId: -1,
      shopGroupId: '',
      searchType: 0,
      searchValue: '',
      sortName: 2,
      sortValue: 0,
      dxmState: 'offline',
      site: '',
      dxmOfflineState: 'waitPublish',
      productSearchType: 1,
      fullCid: '',
      productStatus: '',
      quantityLift: '',
      quantityRight: '',
      advancedTime: 1,
      timeLift: '',
      timeRight: '',
      priceLift: '',
      priceRight: '',
      createId: '',
      advancedSearch: '',
      commentType: 0,
      commentContent: '',
      productStateValue: '',
    },
    responseType: 'document',
  });
}

// 获取产品信息的文档对象
export function getProductInfoDocument<T = Document>(id: string) {
  return request<T, T>({
    url: 'web/popTemuProduct/edit.htm',
    method: 'GET',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: {
      id,
    },
    responseType: 'document',
  });
}

// 发布产品
export interface pushProductInfoResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: string | null;
  // 产品的 id
  data: string;
}
export async function pushProductInfo<T = pushProductInfoResult>(productInfo: ProductInfo, op = 1) {
  const data: ProductInfo & {
    op: number;
  } = {
    op,
    ...productInfo,
  };
  // console.log(data);
  const blob = await toZipBlob(
    JSON.stringify({
      ...data,
    }),
    'popTemuSave.txt',
  );
  return request<T, T>({
    url: 'api/popTemuProduct/add.json',
    method: 'POST',
    data: {
      file: blob,
      op,
    },
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// 上传文件前获取上传的位置
export interface GetSignResult {
  code: number;
  data: {
    msg: string;
    code: number;
    sign: string;
    url: string;
    fileId: string;
    data: null;
    grayUser: boolean;
    leftSize: null;
    treeJson: null;
    videoId: null;
  };
  msg: string | null;
  msgCode: string | null;
}

// 获取上传图片前图片的位置
export async function getSign<T = GetSignResult>(file: File, bucket: string, region: string) {
  return request<T, T>({
    url: 'api/cos/getSign.json',
    method: 'POST',
    data: {
      bucket: bucket,
      region: region,
      fileName: file.name,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
}

// 上传文件
export async function uploadFileToCos<T = any>(url: string, sign: string, file: File) {
  return request<T, T>({
    url,
    method: 'PUT',
    data: file,
    headers: {
      'Content-Type': file.type,
      Authorization: sign,
    },
  });
}

// 上传视频
export async function uploadVideoToCos<T = any>(url: string, sign: string, file: File) {
  return request<T, T>({
    url,
    method: 'PUT',
    data: file,
    headers: {
      'Content-Type': file.type,
      Authorization: sign,
    },
  });
}

// 把图片放置在空间内
export async function cosDxmCallBack<T = any>(
  file: File,
  fullCid: string,
  fileId: string,
  bucket: string,
) {
  return request<T, T>({
    url: 'api/cos/cosDxmCallBack.json',
    method: 'POST',
    data: {
      bucket: bucket,
      fullCid,
      fileId: fileId,
      fileName: file.name,
      isNeedTree: 0,
      fileSize: file.size,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
}

// 获取店小秘的用户信息
export interface GetDianxiaomiUserInfoResult {
  code: number;
  msg: string;
  msgCode: string | null;
  data: {
    id: number;
    account: string;
    accountAlias: string | null;
    puid: number;
    vipLevel: number;
    vipExpired: number;
    state: number;
    wechatBind: boolean;
    shopMap: {
      [key: string]: {
        id: number;
        puid: number;
        name: string;
        apiKey: string | null;
        merchantId: string | null;
        merchantUserName: string | null;
        awsAccessKeyId: string | null;
        marketPlaceId: string | null;
        lastSyncTimeProduct: string | null;
        lastSyncTimeProductOther: string | null;
        lastSyncTimeOrder: string | null;
        lastSyncTimeMessage: string | null;
        lastSyncTimeMessageOutbox: string | null;
        lastSyncTimeFeed: string | null;
        lastSyncTimeDispute: string | null;
        lastSyncTimeCancel: string | null;
        lastSyncTimeReturn: string | null;
        lastSyncTimeMail: string | null;
        lastSyncTimeSmtOrder: string | null;
        lastSyncTimeSmtOrderAll: string | null;
        lastSyncTimeSmtOrderMessage: string | null;
        lastSyncTimeEbayOrder: string | null;
        lastSyncTimeSmtMessage: string | null;
        lastSyncTimeAmazonOrder: string | null;
        orderIndex: number;
        platformIndex: number;
        deletedNum: number;
        platform: string;
        sellerLoginId: string;
        accessToken: string | null;
        refreshToken: string | null;
        refreshTokenTimeout: string | null;
        authTime: string | null;
        createTime: string | null;
        updateTime: string | null;
        isDel: number;
        isExpire: number;
        isNewExpire: boolean | null;
        marketplaceIds: string | null;
        msgNum: number;
        smtAutoOnline: number;
        amazonCountry: string | null;
        countryList: string | null;
        amazonSite: string | null;
        shipmentRemind: string | null;
        expeditingConfig: string | null;
        evaluateConfig: string | null;
        autoCustomerConfig: string | null;
        paymentCareConfig: string | null;
        trackingMsgConfig: string | null;
        newAccessToken: string | null;
        newRefreshToken: string | null;
        newRefreshTokenTimeout: string | null;
        uniqueKey: string | null;
        locationName: string | null;
        locations: string | null;
        publicationNames: string | null;
        ebayAutoOfferConfig: string | null;
        ebayProductPrivileges: string | null;
        childShopList: string | null;
        platformWarehouseList: string | null;
        reviewList: string | null;
        shopSiteList: string | null;
        syncOrderTips: string | null;
        bindWarehouseId: string | null;
        shopCommonSettingList: string | null;
        uid: string | null;
        smtOverSeaModle: boolean;
        pddkjOrderFlag: number;
        idStr: string;
        fruugoNewVersion: boolean;
      };
    };
    platformPermission: string | null;
    shopId: number;
    smtShopId: number;
    permissionList: string[];
    newVersion: boolean;
    secondPick: boolean;
    yuncang: boolean;
    isLabelOld: boolean;
    labelOld: boolean;
  };
  sign: string;
  url: string;
  fileId: string;
  leftSize: string | null;
  treeJson: string | null;
  videoId: string | null;
}
export async function getDianxiaomiUserInfo<T = GetDianxiaomiUserInfoResult>() {
  return request<T, T>({
    url: 'api/userInfo.json',
    method: 'GET',
  });
}

// 获取国家信息
export async function getDianxiaomiProductOrigin<T = Record<string, string>>() {
  return request<T, T>({
    url: 'static/commData/countryCodeData.js?v=1',
    method: 'GET',
  });
}

// 获取省份信息
export async function getDianxiaomRegion2Id<
  T = {
    CN: Record<string, string>;
  },
>() {
  return request<T, T>({
    url: 'static/commData/countryRegionCodeData.js?v=1',
    method: 'GET',
  });
}

// 获取运费模版
export interface GetFreightTemplateIdResult {
  code: number;
  msg: string;
  msgCode: null | string;
  data: Array<{
    id: number;
    puid: number;
    shopId: number;
    site: number;
    freightTemplateId: string;
    templateName: string;
    createTime: number;
    updateTime: number;
  }>;
}
export async function getFreightTemplateId<T = GetFreightTemplateIdResult>(shopId: string) {
  return request<T, T>({
    url: 'api/popTemuCategory/syncTemuShipments.json',
    params: {
      shopId: shopId,
      siteIdStr: 100,
    },
    method: 'POST',
  });
}

// 获取云仓列表
export interface GetWarehouseIdResult {
  code: number;
  msg: string;
  msgCode: null | string;
  data: Array<{
    siteId: number;
    siteName: string;
    warehouseList: Array<{
      id: string;
      name: string;
      managementType: number;
    }>;
  }>;
}
export async function getWarehouseId<T = GetWarehouseIdResult>(shopId: string) {
  return request<T, T>({
    url: 'api/popTemuCategory/warehouseList.json',
    data: {
      shopId: shopId,
      siteIdStr: 100,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 获取说明书的 id
export interface GetInstructionsIdResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: null | string;
  data: {
    instructionsId: string;
    instructionsLanguages: string;
    qualifiedEn: null | string;
  };
}
export async function getInstructionsId<T = GetInstructionsIdResult>(shopId: string, url: string) {
  return request<T, T>({
    url: 'api/popTemuProduct/uploadInstructions.json',
    data: {
      shopId: shopId,
      dxmPdfUr: url,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 新版后批量获取待发布产品的列表的产品信息
export interface BatchGetProductInfoOptions {
  sortName?: number;
  pageNo?: number;
  pageSize?: number;
  searchType?: number;
  searchValue?: string;
  productSearchType?: number;
  shopId?: number;
  dxmState?: string;
  site?: number;
  fullCid?: string;
  sortValue?: number;
  productType?: string;
}

export interface BatchGetProductInfoResult {
  code: number;
  msg: string;
  msgCode: null;
  data: Data;
}

interface Data {
  productParam: ProductParam;
  emailVerify: boolean;
  page: Page;
  isVip: number;
}

interface ProductParam {
  shopId: number;
  fullCid: string;
  dxmState: string;
  dxmOfflineState: string;
  searchType: number;
  searchValue: string;
  sortName: string;
  sortValue: number;
  moveDataState: null;
  site: number;
  productType: null;
  curMoveDataStateNum: null;
  productSearchType: number;
  complianceValue: null;
  priceLift: null;
  priceRight: null;
  quantityType: null;
  quantityLift: null;
  quantityRight: null;
  advancedSearch: null;
  timeLift: null;
  timeRight: null;
  advancedTime: null;
  hasVideo: null;
  dayTime: null;
  stateType: null;
  sortTypeQuote: null;
  sortValueQuote: null;
  productState: null;
  categoryId: null;
  commentContent: null;
  commentType: null;
  sourceUrl: null;
  shopGroupId: null;
  createId: null;
  productStateValue: null;
  compatibilityInfoType: null;
}

interface Page {
  list: DianxiaomiProductInfo[];
  pageNo: number;
  totalPage: number;
  pageSize: number;
  totalSize: number;
  params: Record<string, unknown>;
  msgTimeMap: unknown[];
}

export interface DianxiaomiProductInfo {
  createSource: number;
  id: number;
  puid: number;
  shopId: number;
  categoryId: number;
  categoryIds: null;
  categoryType: null;
  productType: number;
  mainProductSkuSpecReqs: null;
  fullCid: string;
  dxmState: string;
  dxmOfflineState: string;
  productName: string;
  productNameI18n: null;
  description: null;
  productId: number;
  productStateValue: number;
  materialImgUrl: string;
  mainImage: string;
  extraImages: null;
  draftImgUrl: null;
  attributes: null;
  optionValue: null;
  sizeTemplateId: null;
  sizeTemplateIds: null;
  sizeCharts: null;
  goodsModel: null;
  sensitiveAttr: null;
  productOrigin: null;
  region2Id: null;
  originFileUrl: null;
  personalizationSwitch: null;
  customizedTechnologyReq: null;
  outerGoodsUrl: null;
  packageShape: null;
  packageType: null;
  packageImages: null;
  inventoryRegion: null;
  instructionsName: null;
  basePlate: null;
  dxmPdfUrl: null;
  instructionsId: null;
  instructionsTranslateId: null;
  qualifiedEn: null;
  instructionsLanguages: null;
  errMsg: null;
  comment: null;
  commentColor: null;
  sourceUrl: string;
  banjiaShops: null;
  quoteCount: number;
  isCollect: number;
  quoteTime: null;
  createName: string;
  createId: number;
  updateName: string;
  updateId: number;
  onlineTime: null;
  createTime: number;
  updateTime: number;
  dxmScheduleTime: null;
  variations: Variation[];
  variationListStr: string;
  price: null;
  lowPrice: null;
  highPrice: null;
  stock: null;
  lowStock: null;
  highStock: null;
  banjiaShopMap: null;
  sourcePlatform: null;
  sourceSite: null;
  sourceId: null;
  sourceCategoryId: null;
  productSemiManagedReq: string;
  siteValue: number;
  freightTemplateId: null;
  shipmentLimitSecond: null;
  productWarehouseRouteReq: null;
  videoUploadId: null;
  videoUrl: null;
  videoThumbnail: null;
  dxmVideoId: null;
  videoThumbnailHeight: null;
  videoThumbnailWidth: null;
  variantSize: number;
  tempProduct: null;
  optionValueShow: string;
  optionValueShowMap: Record<string, Array<Record<string, string>>>;
  variantTheme: string;
  solutionMsg: null;
  sizeTemplateIdList: null;
  option1: null;
  option1Show: null;
  option2: null;
  option2Show: null;
  option1Value: OptionValue[];
  option2Value: null;
  warehouseInfo: null;
  complianceInfo: null;
  transportTag: null;
  transportSourceProductId: null;
  shipmentUpdate: boolean;
  instructionsUpdate: boolean;
  idStr: string;
  productIdStr: string;
  region2IdStr: null;
  dxmVideoIdStr: null;
  rowIndex: null;
  reTryImg: null;
  semiManagedSiteMode: boolean;
  skuClassificationVo: null;
  packageShapeName: null;
  packageTypeName: null;
  platformProductId: string;
  platformEditUrl: string;
  sensitiveValueList: unknown[];
  platformTitle: string;
  platformDescription: null;
  platformOtherInfo: string;
  platformSite: null;
  platformCategoryId: null;
  platformShortDescription: null;
}

interface Variation {
  id: number;
  puid: number;
  shopId: number;
  dxmProductId: number;
  productId: number;
  productSkcId: number;
  productExtCode: null;
  productSkuId: number;
  skcStatus: null;
  thumbUrl: string;
  skcThumbUrl: null;
  extCode: string;
  supplierPrice: number;
  sitePriceInfo: null;
  productSkuSpecReqs: string;
  length: number;
  width: number;
  height: number;
  weight: number;
  codeType: number;
  code: string;
  productSkuStockQuantityReq: string;
  productSkuWmsInfo: null;
  productSkuNetContent: null;
  numberOfPieces: number;
  skuClassification: number;
  pieceUnitCode: number;
  individuallyPacked: null;
  productSkuAccessories: null;
  suggestedPrice: number;
  suggestedPriceCurrencyType: string;
  stock: number;
  sensitiveAttr: null;
  suggestCloseJit: null;
  errMsg: null;
  createTime: number;
  updateTime: number;
  supplierPriceDouble: number;
  sitePriceInfoDouble: null;
  sitePriceInfoMap: Record<string, unknown>;
  suggestedPriceDouble: number;
  lengthDouble: number;
  widthDouble: number;
  heightDouble: number;
  weightDouble: number;
  attrShow: string;
  attrColorShow: string;
  attrMap: Record<string, string>;
  sensitiveAttrs: null;
  outerGoodsUrl: null;
  newSensitiveAttrs: null;
  virtualStockDiff: null;
  option1: string;
  option2: null;
  updateStock: null;
  importStock: number;
  idStr: string;
}

interface OptionValue {
  id: string;
  name: string;
}
export async function batchGetProductInfo<T = BatchGetProductInfoResult>(
  batchGetProductInfoOptions: BatchGetProductInfoOptions = {},
) {
  const {
    sortName = 2,
    pageNo = 1,
    pageSize = 300,
    searchType = 0,
    searchValue = '',
    productSearchType = 1,
    shopId = -1,
    dxmState = 'offline',
    site = 0,
    fullCid = '',
    sortValue = 2,
    productType = '',
  } = batchGetProductInfoOptions;
  return request<T, T>({
    url: 'api/popTemuProduct/pageList.json',
    data: {
      sortName,
      pageNo,
      pageSize,
      searchType,
      searchValue,
      productSearchType,
      shopId,
      dxmState,
      site,
      fullCid,
      sortValue,
      productType,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 发布前对价格的检测
export interface BatchCheckPriceResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: null;
  data: null;
}
export async function batchCheckPrice<T = BatchCheckPriceResult>({
  dxmState = 'offline',
  platform = 'popTemu',
  ids,
}: {
  dxmState?: string;
  platform?: string;
  ids: string;
}) {
  return request<T, T>({
    url: 'api/priceDetection/batchProtectPriceDetection.json',
    data: {
      dxmState,
      platform,
      ids,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 发布前对违禁词检测
export interface BatchCheckBannedWordResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: null;
  data: null;
}
export async function batchCheckBannedWord<T = BatchCheckBannedWordResult>({
  platform = 'popTemu',
  productIds,
}: {
  platform?: string;
  productIds: string;
}) {
  return request<T, T>({
    url: 'api/bannedWord/batchCheckForBannedWord.json',
    data: {
      platform,
      productIds,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 发布前对产品检测
export interface BatchCheckProductInfoResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: null;
  data: string;
}
export async function batchCheckProductInfo<T = BatchCheckProductInfoResult>({
  platform = 'popTemu',
  ids,
}: {
  platform?: string;
  ids: string;
}) {
  return request<T, T>({
    url: 'api/productCheck/batchCheckProductInfo.json',
    data: {
      platform,
      ids,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}

// 对产品进行发布
export interface BatchPublicResult {
  // 0 表示成功
  code: number;
  msg: string;
  msgCode: null;
  data: {
    successList: Array<{
      id: string;
      msg: null;
      obj: null;
      platformProductId: null;
    }>;
    failList: Array<{
      id: string;
      msg: null;
      obj: null;
      platformProductId: null;
    }>;
    data: number;
  };
}
export async function batchPublic<T = BatchPublicResult>({
  shopId = -1,
  ids,
}: {
  shopId?: number;
  ids: string;
}) {
  return request<T, T>({
    url: 'api/popTemuProduct/batchPublish.json',
    data: {
      shopId,
      ids,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  });
}
